Search a 2D Matrix II

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

For example,

Consider the following matrix:

  1. [
  2. [1, 4, 7, 11, 15],
  3. [2, 5, 8, 12, 19],
  4. [3, 6, 9, 16, 22],
  5. [10, 13, 14, 17, 24],
  6. [18, 21, 23, 26, 30]
  7. ]

Given target = 5, return true.

Given target = 20, return false.

Solution:

  1. public class Solution {
  2. public boolean searchMatrix(int[][] matrix, int target) {
  3. int n = matrix.length, m = matrix[0].length;
  4. int i = 0, j = m - 1;
  5. while (i < n && j >= 0) {
  6. if (matrix[i][j] == target)
  7. return true;
  8. if (target < matrix[i][j])
  9. j--;
  10. else
  11. i++;
  12. }
  13. return false;
  14. }
  15. }